package com.itheima.controller;

import com.itheima.domain.Permission;
import com.itheima.domain.Users;
import com.itheima.service.*;
import com.itheima.service.impl.*;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;

import javax.servlet.ServletException;

import com.itheima.domain.SysLog;
import com.itheima.utils.BeanUtil;
import com.itheima.utils.Uuid;
import lombok.SneakyThrows;

import javax.servlet.annotation.WebServlet;


import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.List;

public class BaseServlet extends HttpServlet {
    protected PermissionService permissionService;
    protected OrdersService ordersService;
    protected SysLogService sysLogService = new SysLogServiceImpl();
    protected String methodName = null;
    protected long executionTime = 0;
    protected String username = null;
    protected ProductService productService;
    protected CityService cityService;
    protected UserService userService;
    protected RoleService roleService;

    @Override
    public void init() throws ServletException {
        permissionService = new PermissionServiceImpl();
        ordersService = new OrdersServiceImpl();
        productService = new ProductServiceImpl();
        cityService = new CityServiceImpl();
        userService = new UserServiceImpl();
        roleService = new RoleServiceImpl();

    }

    @SneakyThrows
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws UnsupportedEncodingException {


        //执行方法前当前毫秒值
        long executionTime1 = System.currentTimeMillis();
        //获取URI
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=UTF-8");
        String uri = req.getRequestURI();
        methodName = uri.substring(uri.lastIndexOf("/") + 1);
        if (uri.equals("/user/login")||uri.contains(".jsp")) {
            Method method = this.getClass().getDeclaredMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
            method.setAccessible(true);
            method.invoke(this, req, resp);
        } else {
            //权限过滤
            filter(req, resp, uri);

            //获取方法对象
            Method method = this.getClass().getDeclaredMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
            method.setAccessible(true);
            method.invoke(this, req, resp);
            //执行方法hou当前毫秒值
            long executionTime2 = System.currentTimeMillis();
            //方法运行毫秒值
            executionTime = executionTime2 - executionTime1;
            //获取session中的登录名(在方法后执行)
            username = (String) req.getSession().getAttribute("username");
            //调用添加方法
            save(username, req, resp);
        }
    }

    //添加方法
    protected void save(String username, HttpServletRequest req, HttpServletResponse resp) throws Exception {
        //获取uri
        String uri = req.getRequestURI();
        //获取访问时间
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String visitTime = sdf.format(new Date());
        //获取访问ip
        String ip = req.getRemoteAddr();
        SysLog sysLog = new SysLog(Uuid.getId(), visitTime, username, ip, uri, executionTime, methodName);
        String subUrl = uri.substring(1, uri.lastIndexOf("/"));
        //判断是否是日志的操作
        if (!subUrl.equals("sysLog")) {
            sysLogService.save(sysLog);
        } else {
            return;
        }

    }


    private void filter(HttpServletRequest req, HttpServletResponse resp, String uri) throws IOException, ServletException {
        Users user = (Users) req.getSession().getAttribute("loginUser");

        Users userPer = userService.findAllPermission(user.getId());

        List<Permission> permissionList = userPer.getPermissionList();


        for (Permission permission : permissionList) {
            if (uri.equals(permission.getUrl())) {
                return;
            }
        }
        resp.setHeader("refresh","0;/errorPermission.jsp");
    }
}
